package com.ophiux.wechat.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;


/**
 * 微信支付签名生成工具类
 * @author chenh
 *2016-11-15
 */
public class WeChatSignUtil {

	
	
	public static Map SignUtilsMap = new HashMap<String,WeChatSignUtil>();
	
	/**
	 * 商户平台 支付接口调用安全秘钥
	 * 商户平台--个人账户--API安全  中获取
	 * 若key传入空则为公用工具类
	 */
	private String api_key;
	
	public WeChatSignUtil(String _api_key){
		this.api_key = _api_key;
	}
	
	
	public static WeChatSignUtil getInstance(String api_key){
		
		WeChatSignUtil signUtil = null;
		if(StringUtil.isEmpty(api_key)){
			//通用型
			api_key = "common";
		}
		/**
		 * 验证对象是否已创建
		 */
		if(SignUtilsMap.containsKey(api_key)){
			 signUtil = (WeChatSignUtil) SignUtilsMap.get(api_key);
		}else{
			 signUtil = new WeChatSignUtil(api_key);
			 SignUtilsMap.put(api_key, signUtil);
		}
		return signUtil;
	}
	
	
	/**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	public String createSign(SortedMap<String, String> packageParams) {
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + this.getApi_key());
		System.out.println("md5 sb:" + sb);
		/**
		 * 字符串转码
		 */
		String sign = MD5Util.MD5Encode(sb.toString(), "")
				.toUpperCase();
		System.out.println("packge签名:" + sign);
		return sign;

	}
	
	/**
	 * 创建SHa1 sign  
	 * 此签名为微信支付前端和支付后台的签名，与微信支付系统无关
	 *  
	 */
	public  String createSHA1Sign(SortedMap<String, String> signParams){
		
		String sha1Sign = "";
		try {
			
			  sha1Sign = Sha1Util.createSHA1Sign(signParams);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			sha1Sign = "签名异常："+e.getMessage();
		}
		return sha1Sign;
	}


	public String getApi_key() {
		return api_key;
	}


	public void setApi_key(String api_key) {
		this.api_key = api_key;
	}
	
	
	public static void main(String[] args) {
		String sb = "appid=wx35a390b81ab01ba6&body=预约挂号/门诊支付&mch_id=1379683702&nonce_str=1559579231&notify_url=http://wx.sxsey.cn:8918/ophiuxAppointDataService/weixingzh/doCallBack.do&openid=oMx83w5WDRYHk9l1xv556GIVt9Ww&out_trade_no=9001201612051458042&spbill_create_ip=223.85.132.23&total_fee=3.0&trade_type=JSAPI&key=sxsdermyy120sxsdermyy120sxsdermy";
		String sign = MD5Util.MD5Encode(sb.toString(), "")
				.toUpperCase();
		System.out.println("packge签名:" + sign);
	}
	
}
